package com.example.demofdfs.util.shell;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import net.neoremind.sshxcute.core.ConnCredential;
import net.neoremind.sshxcute.core.Result;

public class SSHExecCommand implements Command {

    private static JSch jsch = new JSch();;
    private Session session;
    Channel channel = null;

    private String host;
    private String username;
    private String password;
    public static int port = 22;
    
	public SSHExecCommand(String host, String username, String password) {
		this.host = host;
		this.username = username;
		this.password = password;
	}

	@Override
	public Result exec(String command) throws JSchException {
		
		if (session == null || ! session.isConnected())
			connect();
		
        Result result = new Result();
        try {
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            channel.setOutputStream(System.out);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();
            
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder("");
            while (true) {
	            while (in.available() > 0) {
	            	if ((len = in.read(b)) < 0)
	            		break;
	            	sb.append(new String(b, 0, len, "UTF-8"));
	            }
	            if (channel.isClosed()) {
	            	result.sysout = sb.toString();
	            	result.rc = channel.getExitStatus();
            		result.error_msg = new String(baos.toByteArray());
	            	break;
	            }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            channel.disconnect();
        }
		return result;
	}

    /**
     * 连接到指定的IP
     *
     * @throws JSchException
     */
	@Override
    public boolean connect() throws JSchException {
        session = jsch.getSession(username, host, port);
        session.setUserInfo(new ConnCredential(password));
        session.connect(3600000);
        
        return true;
    }

	@Override
	public boolean close() {
		session.disconnect();
		session = null;
		return true;
		
	}
}
